package com.pengliu.controller;

import java.util.List;
import java.util.Map;

import org.apache.commons.lang3.time.DateFormatUtils;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.crypto.password.StandardPasswordEncoder;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.servlet.ModelAndView;

import com.pengliu.common.bean.SysAuth;
import com.pengliu.common.bean.SysAuthExample;
import com.pengliu.common.bean.SysRole;
import com.pengliu.common.bean.SysRoleAuth;
import com.pengliu.common.bean.SysRoleAuthExample;
import com.pengliu.common.bean.SysRoleExample;
import com.pengliu.common.bean.SysUser;
import com.pengliu.common.bean.SysUserExample;
import com.pengliu.common.bean.SysUserRole;
import com.pengliu.common.bean.SysUserRoleExample;
import com.pengliu.common.exception.ServiceException;
import com.pengliu.common.exception.ExceptionEnums;
import com.pengliu.config.BaseController;
import com.pengliu.service.SysAuthService;
import com.pengliu.service.SysRoleAuthService;
import com.pengliu.service.SysRoleService;
import com.pengliu.service.SysUserRoleService;
import com.pengliu.service.SysUserService;
import com.pengliu.service.vo.Menu;
import com.pengliu.util.AjaxResult;
import com.pengliu.util.Constants;
import com.pengliu.util.Lists;
import com.pengliu.util.Maps;

@Controller
@RequestMapping("/admin")
public class AdminController extends BaseController{
	
	@Autowired
	private SysUserService sysUserService;
	
	@Autowired
	private SysRoleService sysRoleService;
	
	@Autowired
	private SysUserRoleService sysUserRoleService;
	
	@Autowired
	private SysAuthService sysAuthService;
	
	@Autowired
	private SysRoleAuthService sysRoleAuthService;
	
	/**
	 * user: pengliu
	 * date: 2017年10月13日
	 * desc: 跳转管理员列表页
	 * @return
	 */
	@RequestMapping("/admin-list")
	public ModelAndView toAdminList(
			@RequestParam(defaultValue="") String username
	) {
		ModelAndView modelAndView = this.getModelAndView("/admin/admin-list");
		
		SysUserExample sysUserExample = new SysUserExample();
		if(!username.isEmpty()) {
			sysUserExample.getCriteria().andUsernameEqualTo(username);
		}
		List<SysUser> listUser = sysUserService.selectByExample(sysUserExample);
		
		List<Map<String,Object>> listMap = Lists.newArrayList();
		
		for (SysUser sysUser : listUser) {
			String roleName = "";
			List<SysRole> listRole = sysUserService.getRoleByUserId(sysUser.getId());
			if(!listRole.isEmpty()) {
				roleName = listRole.get(listRole.size()-1).getName();
			}
			
			Map<String,Object> objMap = Maps.newConcurrentHashMap();
			objMap.put("id", sysUser.getId());
			objMap.put("username", sysUser.getUsername());
			objMap.put("realName", sysUser.getRealName());
			objMap.put("email", sysUser.getEmail());
			objMap.put("phone", sysUser.getPhone());
			objMap.put("roles", roleName);
			objMap.put("isEnabled", sysUser.getIsEnabled());
			objMap.put("lastTime", DateFormatUtils.format(sysUser.getLastTime(), "yyyy-MM-dd HH:mm:ss"));
			objMap.put("createTime", DateFormatUtils.format(sysUser.getCreateTime(), "yyyy-MM-dd HH:mm:ss"));
			listMap.add(objMap);
		}
		modelAndView.addObject("listMap", listMap);
		modelAndView.addObject("search_username", username);
		
		return modelAndView;
	}
	
	/**
	 * user: pengliu
	 * date: 2017年10月13日
	 * desc: 停用管理员
	 * @param id
	 * @return
	 * @throws ServiceException
	 */
	@ResponseBody
	@RequestMapping("/admin_stop")
	public AjaxResult adminStop(
			@RequestParam(required=true) Integer id
	) throws ServiceException {
		SysUser sysUser = sysUserService.selectByPrimaryKey(id);
		
		if(sysUser.getUsername().equals("admin")) {
			throw new ServiceException("超级管理员不能停用");
		}
		
		sysUser.setIsEnabled(false);
		int count = sysUserService.updateByPrimaryKeySelective(sysUser);
		return AjaxResult.getSuccessrResult(count>0);
	}
	
	/**
	 * user: pengliu
	 * date: 2017年10月13日
	 * desc: 启用管理员
	 * @param id
	 * @return
	 */
	@ResponseBody
	@RequestMapping("/admin_start")
	public AjaxResult adminStart(
			@RequestParam(required=true) Integer id
	) {
		SysUser sysUser = sysUserService.selectByPrimaryKey(id);
		sysUser.setIsEnabled(true);
		int count = sysUserService.updateByPrimaryKeySelective(sysUser);
		return AjaxResult.getSuccessrResult(count>0);
	}
	
	/**
	 * user: pengliu
	 * date: 2017年10月13日
	 * desc: 跳转管理员编辑页
	 * @param id
	 * @return
	 */
	@RequestMapping("/admin-edit")
	public ModelAndView adminEdit(@RequestParam(required=true) Integer id) {
		SysUser sysUser = sysUserService.selectByPrimaryKey(id);
		
		SysRole sysRole = null;
		List<SysRole> listSysRole = sysUserService.getRoleByUserId(id);
		if(!listSysRole.isEmpty()) {
			sysRole = listSysRole.get(listSysRole.size()-1);
		}
		
		SysRoleExample example = new SysRoleExample();
		List<SysRole> roles = sysRoleService.selectByExample(example);
		ModelAndView modelAndView = this.getModelAndView("/admin/admin-edit");
		modelAndView.addObject("sysUser", sysUser);
		modelAndView.addObject("sysRole", sysRole);
		modelAndView.addObject("roles", roles);
		return modelAndView;
	}
	
	@ResponseBody
	@RequestMapping("/admin_edit_save")
	public AjaxResult adminEditSave(
			@RequestParam(required=true) Integer id,
			@RequestParam String password,
			@RequestParam String realName,
			@RequestParam String phone,
			@RequestParam String email,
			@RequestParam(required=true) Integer sysRoleId
	) {
		SysUser sysUser = sysUserService.selectByPrimaryKey(id);
		if(!password.isEmpty()) {
			sysUser.setPassword(new StandardPasswordEncoder(Constants.PWDKEY).encode(password));
		}
		sysUser.setRealName(realName);
		sysUser.setPhone(phone);
		sysUser.setEmail(email);
		sysUserService.updateByPrimaryKeySelective(sysUser);
		
		SysUserRoleExample example = new SysUserRoleExample();
		example.getCriteria()
			.andSysUserIdEqualTo(id);
		List<SysUserRole> listSysUserRole = sysUserRoleService.selectByExample(example);
		
		SysUserRole sysUserRole = null;
		
		int count = 0;
		
		if(!listSysUserRole.isEmpty()) {
			sysUserRole = listSysUserRole.get(listSysUserRole.size()-1);
			sysUserRole.setSysRoleId(sysRoleId);
			count = sysUserRoleService.updateByPrimaryKeySelective(sysUserRole);
		}else {
			sysUserRole = new SysUserRole();
			sysUserRole.setSysRoleId(sysRoleId);
			sysUserRole.setSysUserId(sysUser.getId());
			count = sysUserRoleService.insert(sysUserRole);
		}
		return AjaxResult.getSuccessrResult(count>0);
	}
	
	/**
	 * user: pengliu
	 * date: 2018年11月2日
	 * desc: 删除管理员
	 */
	@ResponseBody
	@RequestMapping("/admin_del")
	public AjaxResult adminDel(
			@RequestParam(required=true) Integer id
	) {
		sysUserService.deleteByPrimaryKey(id);
		
		SysUserRoleExample example = new SysUserRoleExample();
		example.getCriteria()
		.andSysUserIdEqualTo(id);
		sysUserRoleService.deleteByExample(example);
		
		return AjaxResult.getSuccessrResult(true);
	}
	
	/**
	 * user: pengliu
	 * date: 2017年10月13日
	 * desc: 跳转管理员新增页
	 * @param id
	 * @return
	 */
	@RequestMapping("/admin-add")
	public ModelAndView adminAddSave() {
		SysRoleExample example = new SysRoleExample();
		List<SysRole> roles = sysRoleService.selectByExample(example);
		ModelAndView modelAndView = this.getModelAndView("/admin/admin-add");
		modelAndView.addObject("roles", roles);
		return modelAndView;
	}
	
	/**
	 * user: pengliu
	 * date: 2017年10月13日
	 * desc: 执行管理员新增操作
	 * @param id
	 * @return
	 * @throws ServiceException 
	 */
	@ResponseBody
	@RequestMapping("/admin_add_save")
	public AjaxResult adminAddSave(
			@RequestParam String username,
			@RequestParam String password,
			@RequestParam String realName,
			@RequestParam String email,
			@RequestParam String phone,
			@RequestParam Integer sysRoleId
	) throws ServiceException {
		SysUserExample sysUserExample = new SysUserExample();
		sysUserExample.getCriteria().andUsernameEqualTo(username);
		SysUser sysUser = sysUserService.selectOneByExample(sysUserExample);
		
		if(null != sysUser) {
			throw new ServiceException(ExceptionEnums.USEREXISTNOTADD); 
		}
		
		if(!password.isEmpty()) {
			password = new StandardPasswordEncoder(Constants.PWDKEY).encode(password);
		}
		
		sysUser = new SysUser();
		sysUser.setUsername(username);
		sysUser.setPassword(password);
		sysUser.setRealName(realName);
		sysUser.setEmail(email);
		sysUser.setPhone(phone);
		sysUser.setIsEnabled(true);
		sysUser.setOperationId(this.getCurrentSysUser().getId());
		int count1 = sysUserService.insert(sysUser);
		
		SysUserRole sysUserRole = new SysUserRole();
		sysUserRole.setSysRoleId(sysRoleId);
		sysUserRole.setSysUserId(sysUser.getId());
		int count2 = sysUserRoleService.insert(sysUserRole);
		
		return AjaxResult.getSuccessrResult(count1>0&count2>0);
	}
	
	/**
	 * user: pengliu
	 * date: 2017年10月13日
	 * desc: 跳转管理员角色页
	 * @param id
	 * @return
	 */
	@RequestMapping("/admin-role")
	public ModelAndView adminRole() {
		SysRoleExample sysRoleExample = new SysRoleExample();
		List<SysRole> listSysRole = sysRoleService.selectByExample(sysRoleExample);
		
		List<Map<String,Object>> listMap = Lists.newArrayList();
		for (SysRole sysRole : listSysRole) {
			Map<String,Object> result = Maps.newConcurrentHashMap();
			result.put("id", sysRole.getId());
			result.put("name", sysRole.getName());
			result.put("remarks", sysRole.getRemarks());
			String usernames = "";
			List<SysUser> listUser = sysRoleService.getSysUserByRoleId(sysRole.getId());
			for (SysUser sysUser : listUser) {
				usernames+=sysUser.getUsername()+"、";
			}
			result.put("usernames", usernames);
			listMap.add(result);
		}
		ModelAndView modelAndView = this.getModelAndView("/admin/admin-role");
		modelAndView.addObject("listMap", listMap);
		return modelAndView;
	}
	
	/**
	 * user: pengliu
	 * date: 2017年10月13日
	 * desc: 跳转管理员角色编辑页
	 * @param id
	 * @return
	 * @throws ServiceException 
	 */
	@RequestMapping("/admin-role-edit")
	public ModelAndView adminRoleEdit(@RequestParam(required=true) Integer sysRoleId) throws ServiceException {
		SysRole sysRole = sysRoleService.selectByPrimaryKey(sysRoleId);
		List<SysAuth> listSysAuth = sysRoleService.getSysAuthByRoleId(sysRoleId);
		
		SysAuthExample sysAuthExample = new SysAuthExample();
		List<SysAuth> allSysAuth = sysAuthService.selectByExample(sysAuthExample);
		
		List<Menu> allMenus = Lists.newArrayList();
		for (SysAuth sysAuth : allSysAuth) {
			Menu menu = new Menu();
			BeanUtils.copyProperties(sysAuth, menu);
			allMenus.add(menu);
		}
		
		List<Menu> menus = treeMenuList(allMenus, 0);
		
		ModelAndView modelAndView = this.getModelAndView("/admin/admin-role-edit");
		modelAndView.addObject("sysRole", sysRole);
		modelAndView.addObject("listSysAuth", listSysAuth);
		modelAndView.addObject("menus", menus);
		return modelAndView;
	}
	
	//菜单树形结构
    public List<Menu> treeMenuList(List<Menu> menuList, Integer parentId) {
    	List<Menu> childMenu = Lists.newArrayList();
    	for (Menu menu : menuList) {
    		Integer menuId = menu.getId();
    		Integer pid = menu.getPid();
    		if (parentId.intValue() == pid.intValue()) {
				List<Menu> c_node = treeMenuList(menuList, menuId);
    			menu.setSubMenu(c_node);
    			childMenu.add(menu);
    		}
		}
        return childMenu;
    }
    
    @ResponseBody
    @RequestMapping("/admin_role_edit")
    public AjaxResult adminRoleEdit(
    		@RequestParam Integer id,
    		@RequestParam String name,
    		@RequestParam String remarks,
    		@RequestParam List<Integer> permissionList
    ) throws ServiceException {
    	SysRole sysRole = sysRoleService.selectByPrimaryKey(id);
    	sysRole.setName(name);
    	sysRole.setRemarks(remarks);
    	sysRoleService.updateByPrimaryKeySelective(sysRole);
    	
    	if(sysRole.getId().intValue() == 1) {
    		SysRoleAuthExample sysRoleAuthExample = new SysRoleAuthExample();
	    	sysRoleAuthExample.getCriteria()
	    		.andSysRoleIdEqualTo(id)
	    		.andSysAuthIdNotIn(Lists.newArrayList(1,2,3,4));
	    	sysRoleAuthService.deleteByExample(sysRoleAuthExample);
	    	
	    	for (Integer authId : permissionList) {
	    		if(authId.intValue() != 1 && authId.intValue() != 2 && authId.intValue() != 3 && authId.intValue() != 4 ) {
	    			SysRoleAuth sysRoleAuth = new SysRoleAuth();
		    		sysRoleAuth.setSysAuthId(authId);
		    		sysRoleAuth.setSysRoleId(id);
		    		sysRoleAuthService.insert(sysRoleAuth);
	    		}
			}
    	} else {
    		SysRoleAuthExample sysRoleAuthExample = new SysRoleAuthExample();
	    	sysRoleAuthExample.getCriteria().andSysRoleIdEqualTo(id);
	    	sysRoleAuthService.deleteByExample(sysRoleAuthExample);
	    	
	    	for (Integer authId : permissionList) {
	    		SysRoleAuth sysRoleAuth = new SysRoleAuth();
	    		sysRoleAuth.setSysAuthId(authId);
	    		sysRoleAuth.setSysRoleId(id);
	    		sysRoleAuthService.insert(sysRoleAuth);
			}
    	}
    	
    	return AjaxResult.getSuccessrResult(true);
    }
    
    
    /**
	 * user: pengliu
	 * date: 2017年10月13日
	 * desc: 跳转管理员角色编辑页
	 * @param id
	 * @return
	 */
	@RequestMapping("/admin-role-add")
	public ModelAndView adminRoleAdd() {
		
		List<SysAuth> listSysAuth = Lists.newArrayList();
		
		SysAuthExample sysAuthExample = new SysAuthExample();
		List<SysAuth> allSysAuth = sysAuthService.selectByExample(sysAuthExample);
		
		List<Menu> allMenus = Lists.newArrayList();
		for (SysAuth sysAuth : allSysAuth) {
			Menu menu = new Menu();
			BeanUtils.copyProperties(sysAuth, menu);
			allMenus.add(menu);
		}
		
		List<Menu> menus = treeMenuList(allMenus, 0);
		
		ModelAndView modelAndView = this.getModelAndView("/admin/admin-role-add");
		modelAndView.addObject("listSysAuth", listSysAuth);
		modelAndView.addObject("menus", menus);
		return modelAndView;
	}
	
	@ResponseBody
    @RequestMapping("/admin_role_add")
    public AjaxResult adminRoleAdd(
    		@RequestParam String name,
    		@RequestParam String remarks,
    		@RequestParam List<Integer> permissionList
    ) {
    	
    	SysRole sysRole = new SysRole();
    	sysRole.setName(name);
    	sysRole.setRemarks(remarks);
    	sysRoleService.insert(sysRole);
    	
    	for (Integer authId : permissionList) {
    		SysRoleAuth sysRoleAuth = new SysRoleAuth();
    		sysRoleAuth.setSysAuthId(authId);
    		sysRoleAuth.setSysRoleId(sysRole.getId());
    		sysRoleAuthService.insert(sysRoleAuth);
		}
    	
    	return AjaxResult.getSuccessrResult(true);
    }
	
	@ResponseBody
    @RequestMapping("/admin_role_del")
    public AjaxResult adminRoleDel(
    		@RequestParam List<Integer> roleIds
    ) throws ServiceException {
		
		if(roleIds.size()==1 && roleIds.get(0).intValue() == 0) {
			throw new ServiceException("无权限用户不可被删除");
		}
		if(roleIds.size()==1 && roleIds.get(0).intValue() == 1) {
			throw new ServiceException("超级管理员不可被删除");
		}
		
		List<Integer> newRoleIds = Lists.newArrayList();
		for (Integer roleId : roleIds) {
			if(roleId.intValue()!=1 && roleId.intValue()!=1) {
				newRoleIds.add(roleId);
			}
		}
		SysRoleExample sysRoleExample = new SysRoleExample();
		sysRoleExample.getCriteria().andIdIn(newRoleIds);
		sysRoleService.deleteByExample(sysRoleExample);
		
    	SysRoleAuthExample sysRoleAuthExample = new SysRoleAuthExample();
    	sysRoleAuthExample.getCriteria().andSysRoleIdIn(newRoleIds);
    	sysRoleAuthService.deleteByExample(sysRoleAuthExample);
    	
    	SysUserRoleExample sysUserRoleExample = new SysUserRoleExample();
    	sysUserRoleExample.getCriteria().andSysRoleIdIn(newRoleIds);
    	//需要删除的 角色和用户关联关系
    	List<SysUserRole> listSysUserRole= sysUserRoleService.selectByExample(sysUserRoleExample);
    	
    	for (SysUserRole sysUserRole : listSysUserRole) {
    		sysUserRole.setSysRoleId(0);
    		sysUserRoleService.updateByPrimaryKeySelective(sysUserRole);
		}
    	
    	return AjaxResult.getSuccessrResult(true);
    }
	
	/**
	 * user: pengliu
	 * date: 2017年10月30日
	 * desc: 进入权限管理页面
	 * @return
	 * @author pengliu
	 */
	@RequestMapping("/admin-auth")
	public ModelAndView adminAuth() {
		
		SysAuthExample sysAuthExample = new SysAuthExample();
		sysAuthExample.setOrderByClause(" sys_auth.pid , sys_auth.rank ");
		List<SysAuth> listSysAuth = sysAuthService.selectByExample(sysAuthExample);
		
		listSysAuth = treeAuthList(listSysAuth, 0);
		
		ModelAndView modelAndView = this.getModelAndView("/admin/admin-auth");
		modelAndView.addObject("listMap", listSysAuth);
		return modelAndView;
	}
	
	//菜单树形排序
    public List<SysAuth> treeAuthList(List<SysAuth> listSysAuth, Integer parentId) {
    	List<SysAuth> childMenu = Lists.newArrayList();
    	for (SysAuth sysAuth : listSysAuth) {
    		if(sysAuth.getPid().intValue()==parentId.intValue()) {
    			List<SysAuth> c_node = treeAuthList(listSysAuth, sysAuth.getId());
    			childMenu.add(sysAuth);
    			for (SysAuth sysAuth_node : c_node) {
    				childMenu.add(sysAuth_node);
				}
    		}
		}
        return childMenu;
    }
}
